//
//  FlutterCarPlayPluginsSceneDelegate.swift
//  flutter_carplay
//
//  Created by Oğuzhan Atalay on 21.08.2021.
//

import CarPlay

@available(iOS 14.0, *)
class FlutterCarPlaySceneDelegate: UIResponder, CPTemplateApplicationSceneDelegate, CPInterfaceControllerDelegate {
  static private var interfaceController: CPInterfaceController?
  
  static public func forceUpdateRootTemplate() {
    print("carplay刷新rootTemplate");
    let rootTemplate = SwiftFlutterCarplayPlugin.rootTemplate
    let animated = SwiftFlutterCarplayPlugin.animated
    
    self.interfaceController?.setRootTemplate(rootTemplate!, animated: animated)
  }
  
  // Fired when just before the carplay become active
  func sceneDidBecomeActive(_ scene: UIScene) {
    print("sceneDidBecomeActive  carplay页面屏幕前台");
    SwiftFlutterCarplayPlugin.onCarplayConnectionChange(status: FCPConnectionTypes.didBecomeActive)
  }

  // Fired when carplay entered background
  func sceneDidEnterBackground(_ scene: UIScene) {
    print("sceneDidEnterBackground  carplay页面后台");
    SwiftFlutterCarplayPlugin.onCarplayConnectionChange(status: FCPConnectionTypes.background)
  }
  
  static public func pop(animated: Bool) {
    self.interfaceController?.popTemplate(animated: animated)
  }
  
  static public func popToRootTemplate(animated: Bool) {
    self.interfaceController?.popToRootTemplate(animated: animated)
  }
  
  static public func push(template: CPTemplate, animated: Bool) {
    self.interfaceController?.pushTemplate(template, animated: animated)
  }
  
  static public func closePresent(animated: Bool) {
    self.interfaceController?.dismissTemplate(animated: animated)
  }

  static public func presentTemplate(template: CPTemplate, animated: Bool,
                                     onPresent: @escaping (_ completed: Bool) -> Void) {
    self.interfaceController?.presentTemplate(template, animated: animated, completion: { completed, error in
      guard error != nil else {
        onPresent(false)
        return
      }
      onPresent(completed)
    })
  }

    
  func templateApplicationScene(_ templateApplicationScene: CPTemplateApplicationScene,
                                didConnect interfaceController: CPInterfaceController) {
    print("templateApplicationScene1  carplay运行");
    FlutterCarPlaySceneDelegate.interfaceController = interfaceController
    
    let rootTemplate = SwiftFlutterCarplayPlugin.rootTemplate
    if rootTemplate == nil {
      let listTemplate = CPListTemplate(title: "", sections: [])
      listTemplate.emptyViewTitleVariants = ["正在启动，请稍后..."]
      interfaceController.setRootTemplate(listTemplate, animated: true)
    }else{
      let animated = SwiftFlutterCarplayPlugin.animated
      interfaceController.setRootTemplate(rootTemplate!, animated: animated)
    }
      
    FlutterCarPlaySceneDelegate.interfaceController!.delegate = self
    SwiftFlutterCarplayPlugin.onCarplayConnectionChange(status: FCPConnectionTypes.connected)
    CPNowPlayingTemplate.shared.add(self)
  }
  
  func templateApplicationScene(_ templateApplicationScene: CPTemplateApplicationScene,
                                didDisconnect interfaceController: CPInterfaceController, from window: CPWindow) {
    print("templateApplicationScene2")
    SwiftFlutterCarplayPlugin.onCarplayConnectionChange(status: FCPConnectionTypes.disconnected)
    CPNowPlayingTemplate.shared.remove(self)
    FlutterCarPlaySceneDelegate.interfaceController = nil
  }
  
  func templateApplicationScene(_ templateApplicationScene: CPTemplateApplicationScene,
                                didDisconnectInterfaceController interfaceController: CPInterfaceController) {
    print("templateApplicationScene3")
    SwiftFlutterCarplayPlugin.onCarplayConnectionChange(status: FCPConnectionTypes.disconnected)
    CPNowPlayingTemplate.shared.remove(self)
    FlutterCarPlaySceneDelegate.interfaceController = nil
  }
    
}

@available(iOS 14.0, *)
extension FlutterCarPlaySceneDelegate : CPNowPlayingTemplateObserver {
    func nowPlayingTemplateUpNextButtonTapped(_ nowPlayingTemplate: CPNowPlayingTemplate) {
        DispatchQueue.main.async {
            FCPStreamHandlerPlugin.sendEvent(type: FCPChannelTypes.onNowPlayingBtnPressed, data: ["elementId": "UpNext"])
        }
    }
    
    func nowPlayingTemplateAlbumArtistButtonTapped(_ nowPlayingTemplate: CPNowPlayingTemplate){
        DispatchQueue.main.async {
            FCPStreamHandlerPlugin.sendEvent(type: FCPChannelTypes.onNowPlayingBtnPressed, data: ["elementId": "AlbumArtist"])
        }
    }
}
